import uuid
from typing import Optional

from fastapi import APIRouter, Body, HTTPException
from pydantic import BaseModel, Field, ValidationError

from app.core.chains import get_introduction_practice_chain,get_introduction_improvement_chain
from app.core.memory.memory_manager import get_session_history

router = APIRouter()


class Introduction_Practice_ChatRequest(BaseModel):
    self_intro: str = Field(..., description="User's question for the knowledge base.")
    conversation_id: Optional[str] = Field(None,
                                           description="A unique ID for the conversation. If not provided, a new one will be generated.")

class Introduction_Practice_ChatResponse(BaseModel):
    answer: str
    score: str
    model: str
    conversation_id: str

class Introduction_Improvement_ChatResponse(BaseModel):
    answer: str
    conversation_id: str

class Introduction_Improvement_ChatRequest(BaseModel):
    question: str
    conversation_id: str

@router.post("/", response_model=Introduction_Practice_ChatResponse)
def knowledge_base_chat(request_data: dict = Body(...)):
    """
    Handles a stateful chat request against the knowledge base.
    Uses conversation_id to maintain context.
    """
    try:
        # 手动验证请求数据
        request = Introduction_Practice_ChatRequest(**request_data['content'])
    except ValidationError as e:
        # 打印详细的验证错误
        print(f"请求数据验证失败: {e.errors()}")
        print(f"收到的请求数据: {request_data}")
        raise HTTPException(status_code=422, detail=e.errors())
    conv_id = request.conversation_id or str(uuid.uuid4())
    print(f"--- KB Chat endpoint called for conversation_id: {conv_id} ---")
    # 获取用户应聘岗位
    chat_history_backend = get_session_history(conv_id)
    introduction_practice_chain = get_introduction_practice_chain()
    enhanced_query = (
        f"用户输入的自我介绍为: {request.self_intro}\n"
    )
    print('enhanced_query:', enhanced_query)

    result = introduction_practice_chain.invoke({
        "input": enhanced_query,
        "chat_history": chat_history_backend.messages
    })

    answer = result.get("answer", "I'm sorry, I couldn't find an answer.")
    print(f"{answer}")
    chat_history_backend.add_user_message(enhanced_query)
    chat_history_backend.add_ai_message(answer)

    answerList =  extract_colon_content(answer)

    print (answerList)

    return Introduction_Practice_ChatResponse(
        score = answerList[0],
        answer= answerList[1],
        model= answerList[2],
        conversation_id=conv_id
    )

@router.post("/chat", response_model=Introduction_Improvement_ChatResponse)
def instruction_improve_chat(request_data: dict = Body(...)):
    """
    Handles a stateful chat request against the knowledge base.
    Uses conversation_id to maintain context.
    """
    try:
        # 手动验证请求数据
        request = Introduction_Improvement_ChatRequest(**request_data)
    except ValidationError as e:
        # 打印详细的验证错误
        print(f"请求数据验证失败: {e.errors()}")
        print(f"收到的请求数据: {request_data}")
        raise HTTPException(status_code=422, detail=e.errors())

    conv_id = request.conversation_id or str(uuid.uuid4())
    print(f"--- KB Chat endpoint called for conversation_id: {conv_id} ---")
    # 获取用户应聘岗位\
    chat_history_backend = get_session_history(conv_id)
    introduction_improvement_chain = get_introduction_improvement_chain()

    print(request.question)

    result = introduction_improvement_chain.invoke({
        "input": request.question,
        "chat_history": chat_history_backend.messages
    })

    answer = result.get("answer", "I'm sorry, I couldn't find an answer.")
    print(f"{answer}")
    chat_history_backend.add_user_message(request.question)
    chat_history_backend.add_ai_message(answer)

    return Introduction_Improvement_ChatResponse(
        answer=answer,
        conversation_id=conv_id
    )

import re

def extract_colon_content(text):
    """提取所有冒号后的内容（支持多行）"""
    pattern = r'(?:^|\n)(?:.*?[:：]\s*)(.*?)(?=(?:\n.*?[:：]|$))'
    matches = re.findall(pattern, text, re.DOTALL)
    return [match.strip() for match in matches]
